package com.chuanyang.driverh.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 图片的工具类
 * @author joyskim
 *
 */
public class BitmapUtil {

	
	private static int crop = 500;// 裁剪大小



	public static Bitmap stringtoBitmap(String string){
		//将字符串转换成Bitmap类型
		Bitmap bitmap=null;
		try {
			byte[]bitmapArray;
			bitmapArray=Base64.decode(string, Base64.DEFAULT);
//			bitmapArray=string.getBytes();
			bitmap=BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);


		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}



	public static String bitmaptoString(Bitmap bitmap){

		//将Bitmap转换成字符串
		String string=null;
		ByteArrayOutputStream bStream=new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG,100,bStream);
		byte[]bytes=bStream.toByteArray();
		string=Base64.encodeToString(bytes,Base64.DEFAULT);
		return string;
	}


	/**
	 * 裁剪图片
	 * @param uri
	 */
	public static void cropPhoto(Activity ac,Uri uri,File file,int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("output", Uri.fromFile(file));
		intent.putExtra("crop", true);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", crop);
		intent.putExtra("outputY", crop);
		ac.startActivityForResult(intent, requestCode);
	}

	/**
	 * 将Bitmap对象写入给定的文件
	 * @param photo
	 */
	public static void saveImage(Bitmap photo, File file) {  
		BufferedOutputStream bos=null;
		try {  
			if(!file.exists()){
				file.createNewFile();
			}
			bos = new BufferedOutputStream(new FileOutputStream(file,false));  
//			photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);  
			photo.compress(CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			try{bos.close();}catch(Exception e1){e1.printStackTrace();}
			e.printStackTrace();
		}
	}

	/**
	 * 使用UIL将本地图片加载显示到ImageView
	 * 注意ImageView又要固定的dp大小才能进行压缩
	 * @param path
	 * @param iv
	 */
	public static void showLocalImg(String path,ImageView iv){
		ImageLoader.getInstance().displayImage(Scheme.FILE.wrap(path), iv, new DisplayImageOptions.Builder()
		.cacheInMemory(true)  //开启内存和磁盘缓存
//		.cacheOnDisk(true)
		.bitmapConfig(Bitmap.Config.ARGB_8888)
		.build());
	}

	/**
	 * 使用UIL将网络图片加载显示到ImageView
	 * @param path
	 * @param iv
	 */
	public static void showImgForNetPath(String path,ImageView iv){
		ImageLoader.getInstance().displayImage(path, iv, new DisplayImageOptions.Builder()
		.cacheInMemory(true)  //开启内存和磁盘缓存
//		.cacheOnDisk(true)
		.bitmapConfig(Bitmap.Config.ARGB_8888)
		.build());
	}

	/**
	 * 使用UIL下载网络路径图片 以便获取bitmap
	 * @param path
	 * @param iv
	 */
	public static void loadToGetBitmapForNetPath(String path,ImageView iv,ImageLoadingListener imageLoadingListener){
		ImageLoader.getInstance().loadImage(path, new DisplayImageOptions.Builder()
		.cacheInMemory(true)  //开启内存和磁盘缓存
//		.cacheOnDisk(true)
		.bitmapConfig(Bitmap.Config.ARGB_8888).build(), imageLoadingListener);
	}

	/**
	 * 将压缩后的图片文件装换为base64字符串 用于上传服务器
	 * @param file
	 * @return
	 */


	public static String compressPicToString(File file) {
		ByteArrayOutputStream bStream=null;
		try{
//			bStream=new ByteArrayOutputStream();
//			Bitmap bit=getImageBitmap(file.getAbsolutePath());
//			bit.compress(CompressFormat.JPEG,100,bStream);
//			byte[]bytes=bStream.toByteArray();
			bStream=getImageBitmap(file.getAbsolutePath());
			byte[]bytes=bStream.toByteArray();
			String str=Base64.encodeToString(bytes,Base64.DEFAULT);
//			bit.recycle();
			return str;
		}catch (Exception e){
			try{bStream.close();}catch(Exception e1){e1.printStackTrace();};
		}finally{
			if (bStream!=null) {
				try {
					bStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	/**
	 * 压缩的是Bitmap的大小
	 * @param srcPath
	 * @return
	 */
	public static ByteArrayOutputStream getImageBitmap(String srcPath) throws Exception{
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
//		int be =  (int) ((w / ww + h/ hh) / 2);
		int be = 1;
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0){
			be = 1;
		}

		newOpts.inSampleSize = be;//设置缩放比例
		newOpts.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap,srcPath);   //压缩好比例大小后再进行质量压缩
	}

	/**
	 * 质量压缩
	 * @param image
	 * @return
	 */
	public  static ByteArrayOutputStream compressImage(Bitmap image,String srcPath) throws Exception{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();//重置baos即清空baos
			options -= 10;//每次都减少10
			if (options<0) {
				break;
			}
			image.compress(CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
		}

		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		saveBitmapToFile(bitmap,srcPath);
		isBm.close();
		return baos;
	}

	public static void saveBitmapToFile(Bitmap bitmap, String _file)
	        throws IOException {BufferedOutputStream os = null;
	    try {
	        File file = new File(_file);  //新建图片
	        int end = _file.lastIndexOf(File.separator);
	        String _filePath = _file.substring(0, end); //获取图片路径
	        File filePath = new File(_filePath);
	        if (!filePath.exists()) {  //如果文件夹不存在，创建文件夹
	            filePath.mkdirs();
	        }
	        file.createNewFile();  //创建图片文件
	        os = new BufferedOutputStream(new FileOutputStream(file));
	        bitmap.compress(CompressFormat.JPEG, 100, os);  //图片存成png格式。
	    } finally {  
	        if (os != null) {  
	            try {  
	                os.close();  //关闭流
	            } catch (IOException e) {  
	            }  
	        }  
	    }  
	}


	/**
	 * 此处没有自适应屏幕压缩
	 *
	 * @param path
	 * @return
	 */
	public static File compressImage(String path, Context context) {
		try {
			//先将图片压缩至手机屏幕分辨率大小；
			Bitmap bitmap = compressImageFromFile(path);
			int quality = 100;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, quality, baos);

			while (baos.toByteArray().length > 50 * 1024) {
				baos.reset();
				quality -= 10;
				bitmap.compress(CompressFormat.JPEG, quality, baos);
			}
			if (TextUtils.isEmpty(getPhotoPath(context))) {
				return null;
			}
			String fileName = getPhotoPath(context);
			File f = new File(fileName);
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(baos.toByteArray());
			fos.flush();
			fos.close();
			if (bitmap != null) {
				bitmap.recycle();
			}
			return f;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 这个方法是得到特定尺寸的图片
	 *
	 * @param srcPath
	 * @return
	 */
	public static Bitmap compressImageFromFile(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;//只读边,不读内容
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = 800f;//
		float ww = 480f;//
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置采样率

		newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
		newOpts.inPurgeable = true;// 同时设置才会有效
		newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		//      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
		//其实是无效的,大家尽管尝试
		return bitmap;
	}
	public static String getPhotoPath(Context context) {
		if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
			PrintUtil.toast(context, "您的手机没有存储卡");
			return "";
		}
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Ehai");
		if (!dir.exists()) {
			dir.mkdir();
		}
		String photoPath = dir.getAbsolutePath() + File.separator +
//				DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
				System.currentTimeMillis() + ".jpg";
		return photoPath;
	}

	/**
	 * 加载网络图片并压缩到屏幕尺寸
	 *
	 * @param url
	 * @param context
	 * @return
	 */
	public static Bitmap compressNetDimension(String url, Context context) {
		try {
			URL myFileUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.connect();

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] b = new byte[1024];
				int len = -1;
				while ((len = is.read(b, 0, 1024)) != -1) {
					baos.write(b, 0, len);
					baos.flush();
				}
				byte[] bytes = baos.toByteArray();
				BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
				options.inSampleSize = ImageUtils.calculateInSampleSize(options, WindowUtils.getScreenWide(context), WindowUtils.getScreenHight(context));
				options.inJustDecodeBounds = false;
				is.close();
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);

			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

}
